package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyComment;
import cn.wolfcode.wolf2w.query.StrategyCommentQueryObject;
import cn.wolfcode.wolf2w.repository.StrategyCommentRepository;
import cn.wolfcode.wolf2w.service.IStrategyCommentService;
import cn.wolfcode.wolf2w.util.DBHelp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
//@Transactional
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public void save(StrategyComment strategyComment) {
        strategyComment.setId(null);
        strategyComment.setCreateTime(new Date());
        repository.save(strategyComment);

    }

    @Override
    public void update(StrategyComment strategyComment) {
        repository.save(strategyComment);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public StrategyComment get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyComment> list() {
        return repository.findAll();
    }

    @Override
    public Page<StrategyComment> query(StrategyCommentQueryObject qo) {
        Query query = new Query();

        if(StringUtils.hasLength(qo.getStrategyId())){
            query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
        }

        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "createTime");
        return DBHelp.query(template, StrategyComment.class,pageable,query);
    }

    @Override
    public void commentThumb(String cid, String uid) {
        //获取点赞集合
        StrategyComment comment = this.get(cid);
        List<String> thumbuplist = comment.getThumbuplist();

        //判断uid是否在集合中
        if (thumbuplist.contains(uid)){
            //在,点赞数-1并移除
            comment.setThumbupnum(comment.getThumbupnum()-1);
            thumbuplist.remove(uid);
        }else {
            //不在,点赞数+1并移除
            comment.setThumbupnum(comment.getThumbupnum()+1);
            thumbuplist.add(uid);
        }

        //更新
        this.update(comment);

    }


}
